package org.suwenqian.audiovideosummary.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.suwenqian.audiovideosummary.common.enums.ProcessStepEnum;
import org.suwenqian.audiovideosummary.dao.entity.FileAsset;
import org.suwenqian.audiovideosummary.dao.entity.ProgressLog;
import org.suwenqian.audiovideosummary.dao.mapper.FileAssetMapper;
import org.suwenqian.audiovideosummary.dao.mapper.ProgressLogMapper;
import org.suwenqian.audiovideosummary.dto.req.AsrEndReqDTO;
import org.suwenqian.audiovideosummary.dto.req.TranscodeReqDTO;
import org.suwenqian.audiovideosummary.service.CallBackService;
import org.suwenqian.audiovideosummary.service.ProgressLogService;
import org.suwenqian.audiovideosummary.service.llm.LLMService;
import org.suwenqian.audiovideosummary.util.VideoUtils;

import java.util.Date;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CallBackServiceImpl extends ServiceImpl<FileAssetMapper, FileAsset>  implements CallBackService {

    private final TransactionTemplate transactionTemplate;
    private final ProgressLogMapper progressLogMapper;
    private final ProgressLogService progressLogService;
    private final FileAssetMapper fileAssetMapper;
    private final LLMService llmService;

    @Override
    public void transcodeEnd(TranscodeReqDTO requestParam) {
        Snowflake snowflake = SpringUtil.getBean(Snowflake.class);
        // 1.写库 + 更新日志
        transactionTemplate.executeWithoutResult(transactionStatus -> {
            try{
                FileAsset fileAsset = FileAsset.builder()
                        .id(snowflake.nextId())
                        .taskId(requestParam.getTaskId())
                        .type(requestParam.getFile().getOriginalFilename())
                        .kodoHash(requestParam.getHash())
                        .kodoKey(requestParam.getKey())
                        .versionNo(1)
                        .sizeByte(requestParam.getFile().getSize())
                        .durationMs(VideoUtils.getVideoDuration(requestParam.getFile()))
                        .createdAt(new Date())
                        .build();
                fileAssetMapper.insert(fileAsset);
            }catch (Exception e){
                transactionStatus.setRollbackOnly();
            }
        });
        Optional.ofNullable(progressLogMapper.selectOne(
                Wrappers.lambdaQuery(ProgressLog.class)
                        .eq(ProgressLog::getTaskId, requestParam.getTaskId())
        )).ifPresent(log -> {
            log.setStep(ProcessStepEnum.TRANSCODE);
            log.setPercent(ProcessStepEnum.TRANSCODE.getPercent());
            log.setMessage(ProcessStepEnum.TRANSCODE.getDescription());
            progressLogService.sendProgress(log);

        });
    }

    @Override
    public void asrEnd(AsrEndReqDTO requestParam) {
        Snowflake snowflake = SpringUtil.getBean(Snowflake.class);
        // 1.写库 + 更新日志
        transactionTemplate.executeWithoutResult(transactionStatus -> {
            try{
                FileAsset fileAsset = FileAsset.builder()
                        .id(snowflake.nextId())
                        .taskId(requestParam.getTaskId())
                        .type(requestParam.getFile().getOriginalFilename())
                        .kodoKey(requestParam.getKey())
                        .kodoHash(requestParam.getHash())
                        .sizeByte(requestParam.getFile().getSize())
                        .versionNo(1)
                        .createdAt(new Date())
                        .build();
                fileAssetMapper.insert(fileAsset);
            }catch (Exception e){
                transactionStatus.setRollbackOnly();
            }
        });

        Optional.ofNullable(progressLogMapper.selectOne(
                Wrappers.lambdaQuery(ProgressLog.class)
                        .eq(ProgressLog::getTaskId, requestParam.getTaskId())
        )).ifPresent(log -> {
            log.setStep(ProcessStepEnum.ASR);
            log.setPercent(ProcessStepEnum.ASR.getPercent());
            log.setMessage(ProcessStepEnum.ASR.getDescription());
            progressLogService.sendProgress(log);
        });
        // 2. 调用大模型生成总结摘要，关键词和思维导图
        llmService.doLLM(requestParam);
    }
}
